package cn.hfatec.shms.web.ss.ssCriteria.service;

import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.base.BaseDao;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.system.codeInfo.model.CodeInfo;
import cn.hfatec.shms.web.ss.ssCriteria.dao.SsCriteriaDao;
import cn.hfatec.shms.web.ss.ssCriteria.model.SsCriteria;
import cn.hfatec.shms.web.ss.ssCriteria.model.SsCriteriaParams;

import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.beanutils.BeanUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import static cn.hfatec.shms.web.Rule.*;


/**
 *
 * @author hfatec
 * @version 1.0
 *
 * the JAVA code is generate by middlegen
 *
 */
@Service("SsCriteriaService")
public class SsCriteriaService {

    public static final String BEAN_ID = "SsCriteriaService";

    //注入Dao层
    @Resource(name = "SsCriteriaDao")
    private SsCriteriaDao ssCriteriaDao;

    //注入BaseDao
    @Resource(name = "BaseDao")
    private BaseDao baseDao;

    @Transactional
    public static String encodeFilename(HttpServletRequest request, String fileName) {
        String rtn = "";
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String new_filename = URLEncoder.encode(fileName, "UTF8");

            rtn = "filename=\"" + new_filename + "\"";

            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();

                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                } else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } else if (userAgent.indexOf("applewebkit") != -1) {
                    new_filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
        } catch (UnsupportedEncodingException e) {
            try {
                rtn = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException localUnsupportedEncodingException1) {
            }
        }
        return rtn;
    }

    /**
     *
     * 查询数据
     *
     * @param ssCriteriaParams
     * @param page
     *
     */
    @Transactional
    public Table querySsCriteriaTable(SsCriteriaParams ssCriteriaParams, Page page){

        HashMap<String, Object> params = new HashMap<String, Object>();
        if(ssCriteriaParams.getSpareC()!=null && ssCriteriaParams.getSpareC().equals("0"))
            ssCriteriaParams.setSpareC("");
        params.put("params", ssCriteriaParams);
        return baseDao.queryTableByPage("querySsCriteria", params, page);
    }

    /**
     *
     * 查询数据
     *
     * @param ssCriteriaParams
     * @param page
     *
     */
    @Transactional
    public Table queryResultTable(SsCriteriaParams ssCriteriaParams, Page page){

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", ssCriteriaParams);
        return baseDao.queryTableByPage("queryResult", params, page);
    }

    /**
     *
     * 插入数据
     * @param ssCriteria
     *
     */
    @Transactional
    public void saveSsCriteria(SsCriteria ssCriteria) {
        if(ssCriteria.getId() != null) {
            SsCriteria result = getSsCriteria(ssCriteria.getId());
            if(result != null) {
                ssCriteriaDao.update(ssCriteria);
            } else {
                ssCriteriaDao.insert(ssCriteria);
            }
        } else {
            ssCriteriaDao.insert(ssCriteria);
        }
    }

    /**
     *
     * 删除数据
     * @param id
     *
     */
    @Transactional
    public void deleteSsCriteria(Integer id) {

        ssCriteriaDao.delete(id);
    }

    /**
     *
     * 删除数据
     * @param ssCriteriaList
     *
     */
    @Transactional
    public void deleteSsCriteriaBatch(List<String> ssCriteriaList) {
        for(String id : ssCriteriaList) {
            deleteSsCriteria(Integer.valueOf(id));
        }
    }

    /**
     *
     * 根据ID获取数据
     * @param id
     *
     */
    @Transactional
    public SsCriteria getSsCriteria(Integer id) {

        return ssCriteriaDao.getSsCriteriaById(id);
    }

    /**
     * 根据ID获取数据
     *
     * @param billId
     */
    @Transactional
    public List<SsCriteria> getSsCriteriaBillId(String billId) {

        return ssCriteriaDao.getSsCriteriaByBillId(billId);
    }

    /**
     * 根据ID获取数据
     *
     * @
     */
    @Transactional
    public List<SsCriteria> difCriteria() {

        return ssCriteriaDao.getDifCriteria();
    }

    /**
     * @param testDate
     * @param testEnd
     */
    @Transactional
    public List<SsCriteria> getCustomerTestDate(String testDate, String testEnd) {
        return ssCriteriaDao.getTestDate(testDate, testEnd);
    }

    public void Compare(String testDate, String testEnd) throws  IllegalAccessException, InvocationTargetException {
        List<SsCriteria> ssCriteria=  difCriteria();
        if (ssCriteria != null && !ssCriteria.isEmpty()) {
            for (SsCriteria criteria : ssCriteria) {
                saveSsCriteria(criteria);
            }}
        List<SsCriteria> testCriteria = getCustomerTestDate(testDate, testEnd);
        int i = 0;   int k=0;
        if (testCriteria != null && !testCriteria.isEmpty()) {
            for (SsCriteria test : testCriteria) {
                List<SsCriteria> ssCriteriasList = getSsCriteriaBillId(test.getBillId());
                if (ssCriteriasList != null && !ssCriteriasList.isEmpty()) {
                    SsCriteria Zero = new SsCriteria();
                    SsCriteria Fister = new SsCriteria();
                    SsCriteria storage = new SsCriteria();
                    if (ssCriteriasList.size() >= 2) {
                        for (SsCriteria ssCriterias : ssCriteriasList) {

                            if (ssCriterias.getVipFh().equals("0")) {
                               BeanUtils.copyProperties(Zero, ssCriterias);

                            } else {
                                k=0;
                                BeanUtils.copyProperties(Fister, ssCriterias);
                                BeanUtils.copyProperties(storage, ssCriterias);
                                if (Fister.getBmi()!=null && Zero.getBmi()!=null && Fister.getBmi().length()!=0 && Zero.getBmi().length()!=0) {
                                    i = contrastBmi(Double.valueOf(Zero.getBmi()),Double.valueOf(Fister.getBmi()));
                                    storage.setBmi(String.valueOf(i));
                                    k=1;
                                } else {
                                    storage.setBmi("0");

                                }
                                if ( Fister.getTriglyceride()!=null && Zero.getTriglyceride()!=null && Fister.getTriglyceride().length()!=0 && Zero.getTriglyceride().length()!=0) {
                                    i = contrastTg(Double.valueOf(Zero.getTriglyceride()),Double.valueOf(Fister.getTriglyceride()) );
                                    storage.setTriglyceride(String.valueOf(i));
                                    k=1;
                                } else {
                                    storage.setTriglyceride("0");

                                }
                                if ( Fister.getCholesterol()!=null && Zero.getCholesterol()!=null && Fister.getCholesterol().length()!=0 && Zero.getCholesterol().length()!=0) {
                                    i = contrastTc( Double.valueOf(Zero.getCholesterol()),Double.valueOf(Fister.getCholesterol()));
                                    storage.setCholesterol(String.valueOf(i));
                                    k=1;
                                } else {
                                    storage.setCholesterol("0");

                                }
                                if (Fister.getBloodSugar()!=null && Zero.getBloodSugar()!=null && Fister.getBloodSugar().length()!=0 && Zero.getBloodSugar().length()!=0) {
                                    i = contrastFpg(Double.valueOf(Zero.getBloodSugar()),Double.valueOf(Fister.getBloodSugar()));
                                    storage.setBloodSugar(String.valueOf(i));
                                    k=1;
                                } else {
                                    storage.setBloodSugar("0");

                                }
                                if (Fister.getSystolicPressure()!=null && Zero.getSystolicPressure()!=null && Fister.getSystolicPressure().length()!=0 && Zero.getSystolicPressure().length()!=0) {
                                    i = contrastSbp(Double.valueOf(Zero.getSystolicPressure()),Double.valueOf(Fister.getSystolicPressure()));
                                    storage.setSystolicPressure(String.valueOf(i));
                                    k=1;
                                } else {
                                    storage.setSystolicPressure("0");

                                }
                                if (Fister.getDiastolicPressure()!=null && Zero.getDiastolicPressure()!=null && Fister.getDiastolicPressure().length()!=0 && Zero.getDiastolicPressure().length()!=0) {
                                    i = contrastDbp( Double.valueOf(Zero.getDiastolicPressure()),Double.valueOf(Fister.getDiastolicPressure()));
                                    storage.setDiastolicPressure(String.valueOf(i));
                                    k=1;
                                } else {
                                    storage.setDiastolicPressure("0");

                                }
                                if(k==0){
                                    storage.setSpareB("无");
                                }else{
                                    storage.setSpareB("有");
                                }
                                saveSsCriteria(storage);



                            }


                        }


                    }
                }
            }

        }
    }

    /**
     * 导出
     *
     * @param
     */
    @Transactional
    public String exportExcel(SsCriteriaParams ssCriteriaParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            String clientFileName = encodeFilename(request, System.currentTimeMillis() + "");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; " + clientFileName + ".xls");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream os = response.getOutputStream();
            List dataList = ssCriteriaDao.querySsCriteria(ssCriteriaParams);
            List nameList = new ArrayList();
            Calendar c = Calendar.getInstance();
            int weeknum = c.get(Calendar.WEEK_OF_YEAR);
            nameList.add("客户姓名");
            nameList.add("电话");
            nameList.add("大类");
            nameList.add("产品名称");
            nameList.add("渠道");
            nameList.add("下单日期");
            nameList.add("开卡日期");
            nameList.add("结束日期");
            nameList.add("引荐人");
            nameList.add("促会人");
            nameList.add("分管人");
            nameList.add("周期");
            nameList.add("测试日期");
            nameList.add("舒张压");
            nameList.add("收缩压");

            nameList.add("BMI");
            nameList.add("空腹血糖");

            nameList.add("甘油三酯");
            nameList.add("胆固醇");
            nameList.add("总分");
            nameList.add("评定结果");
            this.exportExcel(nameList, dataList, os);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * @return HSSFWorkbook
     */
    public HSSFWorkbook createWorkbook(List fieldName, List fieldData) {
        List<CodeInfo> sexList = CodeInfoCache.getCodeInfo(CodeType.SEX);
        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("评分结果");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        HSSFCellStyle cellstyle = (HSSFCellStyle) wb.createCellStyle();// 设置表头样式
        cellstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 设置垂直居中
        cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置水平居中
        cellstyle.setWrapText(true); // 设置为自动换行
        HSSFFont cellFont = (HSSFFont) wb.createFont(); // 创建表头字体样式
        cellFont.setFontHeightInPoints((short) 10); // 设置字体大小
        cellFont.setFontName("宋体"); // 设置字体类型
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
        cellstyle.setFont(cellFont); // 为表头样式设置字体样式


        for (int i = 0; i < fieldName.size(); i++) {
            HSSFCell cell = row.createCell((short) i);
            cell.setCellValue((String) fieldName.get(i));
            cell.setCellStyle(cellstyle);
        }

        SsCriteria ssCriteria = null;

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，

        for (int i = 0; i < fieldData.size(); i++) {
            row = sheet.createRow(i + 1);
            ssCriteria = (SsCriteria) fieldData.get(i);
            // 第四步，创建单元格，并设置值
            String[] nameArry = {ssCriteria.getCustomerName(), ssCriteria.getPhone(), ssCriteria.getVipType(), ssCriteria.getProductName(), ssCriteria.getChannelType(), ssCriteria.getBillTime(), ssCriteria.getBillStart(), ssCriteria.getBillEnd(),
                    ssCriteria.getYjName(), ssCriteria.getChName(), ssCriteria.getFgName(), ssCriteria.getVipFh(), ssCriteria.getTestDate(), ssCriteria.getDiastolicPressure(), ssCriteria.getSystolicPressure(),
                     ssCriteria.getBmi(), ssCriteria.getBloodSugar(), ssCriteria.getTriglyceride(), ssCriteria.getCholesterol(), ssCriteria.getSpareA(),ssCriteria.getSpareB()};
            for (int j = 0; j < nameArry.length; j++) {
                if (nameArry[j] == null) {
                    row.createCell((short) j).setCellValue("");
                } else {
                    row.createCell((short) j).setCellValue(nameArry[j]);
                }

            }
        }
        //自适应列宽
        for (int i = 0; i < fieldName.size(); i++) {
            sheet.autoSizeColumn((short) i);
        }
        return wb;
    }

    //将信息写入输出流的方法。
    public void exportExcel(List fieldName, List fieldData, OutputStream os) throws Exception {
        HSSFWorkbook wb = createWorkbook(fieldName, fieldData);
        wb.write(os);
        os.close();
    }
}